package com.topisv.tms.web.stockchange;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.stockchange.StockChangeBill;
import com.topisv.tms.entity.stockchange.StockChangeBillItem;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.qmservice.StockChangeService;
import com.topisv.tms.service.stockChange.StockChangeBillService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.utils.vo.StockChangeBillVo;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 库存异动单_control
 * @author gh
 *
 */
@Controller
@RequestMapping(value = "/stockChangeBill")
public class StockChangeBillController extends BaseDataTableController{
	
	@Autowired
	private StockChangeBillService scbService;
	
	@RequestMapping(value = "v2_stockChangePage")
	public String warehouseAgePage(Model model, ServletRequest request,
			ServletResponse response) {
		fillSelectValue(model, null);
		return "/stockChangeBill/stockChangePage";
	}
	@RequestMapping(value = "v2_toSaveStockChangeBillPage")
	public String toSaveStockChangeBillPage(@RequestParam(value = "id",required=false) Long id,Model model, ServletRequest request,
			ServletResponse response) {
		fillSelectValue(model, null);
		if(id!=null&&id!=0){
			StockChangeBill scb = scbService.queryById(id);
			model.addAttribute("scb",scb );
			List<StockChangeBillItem> scbiList = scbService.findItemByBillCode(scb.getBillCode());
			model.addAttribute("scbiList", scbiList);
		}
		return "/stockChangeBill/addStockChangeBillPage";
	}
	
	@RequestMapping(value = "queryStockChange")
	public void queryStockChange(@RequestBody JSONParam[] paramJson,HttpServletRequest request, 
			HttpServletResponse response) {
		JSONObject json=new JSONObject();
		Page<StockChangeBill> page=null;
		PrintWriter out=null;
		try{
			//变量定义
			out=response.getWriter();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			//查询
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int pageSize = Integer.parseInt(paramMap.get("iDisplayLength")); 
			int pageNumber=(start/pageSize)+1;
			
			String warehouseCode = paramMap.get("warehouseCode");
			StockChangeBill scb = new StockChangeBill();
			scb.setWarehouseCode(warehouseCode);
			page = scbService.findTable(scb, pageNumber, pageSize);
			List<StockChangeBill> stccList = page.getContent();

			//封装查询结果
	        json.put("aaData", stccList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
		} catch (Exception e) {
			log.error("查询异常",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	@RequestMapping(value = "deleteStockChangeBill")
	public void deleteStockChangeBill(@RequestParam(value = "id") String id,Model model, ServletRequest request,
			ServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			
			scbService.delete(Long.valueOf(id));
			
			json.put("msg", "success");
			json.put("content", "删除成功");
		} catch (NumberFormatException e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		} catch (Exception e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		}
		fillSelectValue(model, null);
		out.print(json.toString());
	}
	
	
	@RequestMapping(value = "v2_saveStockChange")
	public String saveStockChange(@ModelAttribute("vo")StockChangeBillVo scbVo,Model model, ServletRequest request,
			ServletResponse response) {
		String result = "";
		String errorMsg = "";
		try{
			fillSelectValue(model, null);
			if(scbVo==null||scbVo.getScb()== null){
			}else {
				if(scbVo.getScbiList().size()==0){
					model.addAttribute("errorMsg", "数据填写异常");
					model.addAttribute("result", "error");
					model.addAttribute("scb",scbVo.getScb() );
					model.addAttribute("scbiList", scbVo.getScbiList());
					return "/stockChangeBill/addStockChangeBillPage";
				}
				List<StockChangeBillItem> scbiDelList = new ArrayList<StockChangeBillItem>();
				List<StockChangeBillItem> scbiList = scbVo.getScbiList();
				for (StockChangeBillItem scbi : scbiList) {
					if(StringUtils.isEmpty(scbi.getInventoryType())&&StringUtils.isEmpty(scbi.getSku())&&
							scbi.getQuantity()==null){
						scbiDelList.add(scbi);
					}
				}
				scbiList.removeAll(scbiDelList);
				
				result = scbService.save(scbVo);
				if(!"success".equals(result)){
					String orderTypeStr = "";
					if("INSTORAGE".equals(scbVo.getScb().getOrderType())) {
						orderTypeStr = "入库单";
					}else {
						orderTypeStr = "销售订单";
					}
					if("bill_not_exist".equals(result)){
						errorMsg = orderTypeStr+"单号不存在";
					}else if(result!=null&&result.indexOf("sku_not_exist_")!=-1) {
						errorMsg = "第"+result.substring(result.lastIndexOf("_")+1)+"行SKU不存在";
					}
					
					model.addAttribute("errorMsg", errorMsg);
					model.addAttribute("result", result);
					model.addAttribute("scb",scbVo.getScb() );
					model.addAttribute("scbiList", scbVo.getScbiList());
					return "/stockChangeBill/addStockChangeBillPage";
				}
			}
		}catch(Exception e){e.printStackTrace();
			log.error("保存异动单异常",e);
			model.addAttribute("errorMsg", "系统错误");
			model.addAttribute("result", "error");
			model.addAttribute("scb",scbVo.getScb() );
			model.addAttribute("scbiList", scbVo.getScbiList());
			return "/stockChangeBill/addStockChangeBillPage";
		}
		return "redirect:/stockChangeBill/v2_stockChangePage";
	}
	
	@Resource(type=StockChangeService.class)
	private QmRequestSender<StockChangeBill> stockChangeService;
	@RequestMapping(value = "v2_sendQmStockChange")
	public void sendQmStockChange(@RequestParam(value = "id") String id,Model model, ServletRequest request,
			ServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out=response.getWriter();
			json=new JSONObject();
			
			StockChangeBill scb = scbService.queryById(Long.valueOf(id));
			String result = stockChangeService.send(scb, scb.getCustomerCode());
			if(!"success".equals(result)&&!"failure".equals(result)) {
				log.error("异动单推送失败"+result);
				json.put("msg", "fail");
				json.put("content", "推送失败("+result+")");
				out.print(json.toString());
				return;
			}
			scbService.sendStockChangeBill(scb.getId());
			
			json.put("msg", "success");
			json.put("content", "推送成功");
		} catch (NumberFormatException e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		} catch (Exception e) {
			log.error("查询异常",e);
			json.put("msg", "fail");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	
}
